package com.ming.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.study.exceptionHandler.MingException;
import com.ming.study.pojo.User;
import com.ming.study.mapper.UserMapper;
import com.ming.study.pojo.UserInfo;
import com.ming.study.pojo.vo.UserLoginVo;
import com.ming.study.service.JwService;
import com.ming.study.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.study.utils.JwtUtils;
import com.ming.study.utils.ResultCode;
import com.ming.study.utils.ResultCodeImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mingyue
 * @since 2020-12-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private JwService jwService;

    /**
     * 登录
     * @param userLoginVo
     * @return
     */
    @Override
    public String loginOrRegister(UserLoginVo userLoginVo) {
        String userAccount = userLoginVo.getUserAccount();
        String userPassword = userLoginVo.getUserPassword();
        // 账号密码不为空
        if(StringUtils.isEmpty(userAccount) || StringUtils.isEmpty(userPassword)) {
            throw new MingException(ResultCodeImpl.ERROR_LOGIN_PARAM_LACK);
        }
        // 判断是否正确
        boolean isCorrect = jwService.login(userLoginVo);
        User user;
        if(isCorrect) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_account", userAccount);
            user = this.getOne(userQueryWrapper);
            if(user != null && !user.getUserPassword().equals( userLoginVo.getUserPassword() )) { // 密码改变，修改
                user.setUserPassword( userLoginVo.getUserPassword() );
            } else if(user == null) { // 没有则新建
                user = new User();
                user.setUserAccount( userLoginVo.getUserAccount() );
                user.setUserPassword( userLoginVo.getUserPassword() );
                this.save(user);
            }
        } else {
            throw new MingException(ResultCodeImpl.ERROR_LOGIN_USER_NOT_FOUND);
        }
        String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getUserAccount());
        return jwtToken;
    }

    @Override
    public UserInfo getUserInfo() {
        return null;
    }



}
